<template>
  <Card class="meta-attr" :bordered="false">
    <div class="flex-row-center-start">
      <InputSearch
        placeholder="search"
        v-model:value="searchValue"
        style="margin: 8px; width: 500px"
      />
      <div style="margin-left: 100px">
        <Button style="margin-right: 10px" @click="handleAdd('')">新增</Button>
        <Button :type="'primary'" @click="handleQuery">刷新</Button>
      </div>
    </div>

    <Spin :spinning="spinning">
      <Tree
        v-if="treeData.length"
        :tree-data="treeData"
        :field-names="fieldNames"
        :expanded-keys="expandedKeys"
        :auto-expand-parent="autoExpandParent"
        @expand="handleExpand"
      >
        <template #title="record">
          <div class="flex-row-center-start" @click="handleTreeNodeClick(record.id)">
            <span v-if="record.cnName && record.cnName.indexOf(searchValue) > -1">
              {{ record['cnName'].substring(0, record['cnName'].indexOf(searchValue)) }}
              <span style="color: #f50">{{ searchValue }}</span>
              {{
                record['cnName'].substring(
                  record['cnName'].indexOf(searchValue) + searchValue.length,
                )
              }}
            </span>
            <span v-else>{{ record['cnName'] }}</span>
            <div v-if="curId === record.id" style="margin-left: 50px">
              <Tag color="blue" @click="handleAdd(record.id)">添加</Tag>
              <Tag color="green" @click="handleEdit(record)">更新</Tag>
              <Tag color="red" @click="handleDel(record.id, record.childBizMetaAttrList)">删除</Tag>
            </div>
          </div>
        </template>
      </Tree>
    </Spin>

    <MetaAttrModal
      :tree-flat-data="treeFlatData"
      @register="registerModal"
      @success="handleSuccess"
    />
  </Card>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue';
  import MetaAttrModal from './modal.vue';
  import mcApi from 'mc-c2b2m-operator-api';
  import { useModal } from '@/components/Modal';
  import { useMessage } from '@/hooks/web/useMessage';
  import { BizMetaAttrTreeModel } from 'mc-c2b2m-operator-api/types/spu';
  import { Tag, Card, Tree, Button, Spin, InputSearch } from 'ant-design-vue';

  const { SpuModule } = mcApi;
  const { BizMetaArrApi } = SpuModule;

  const { createMessage } = useMessage();
  const [registerModal, { openModal, closeModal }] = useModal();

  // 加载状态
  const spinning = ref<boolean>(false);
  // 搜索关键词
  const searchValue = ref<string>('');
  // 展开索引列表
  const expandedKeys = ref<any>([]);
  // 是否自动展开父节点
  const autoExpandParent = ref<boolean>(true);
  // 替换树字段
  const fieldNames = ref<any>({ children: 'childBizMetaAttrList', title: 'cnName', key: 'id' });
  // 树数据源
  const treeData = ref<any>([]);
  // 扁平化的树数据源
  const treeFlatData = ref<any>([]);
  // 当前点击的树节点id
  const curId = ref<string>('');
  // 初始化查询
  handleQuery();

  // 监听搜索值
  watch(
    searchValue,
    (value) => {
      handleExpandedKeys(value);
      searchValue.value = value;
      autoExpandParent.value = true;
    },
    {
      immediate: true,
    },
  );
  // 查询业务元信息树
  function handleQuery() {
    curId.value = '';
    spinning.value = true;
    searchValue.value = '';
    BizMetaArrApi.getBizMetaAttrTree()
      .then((res: BizMetaAttrTreeModel[]) => {
        treeData.value = res || [];
        handleTreeFlatData(treeData.value);
        handleExpandedKeys('');
      })
      .finally(() => {
        spinning.value = false;
      });
  }
  // 处理扁平化树数据源
  function handleTreeFlatData(data: any) {
    data?.forEach?.((item: any) => {
      const { id, cnName, parentId, parentCnName, childBizMetaAttrList: children } = item;
      treeFlatData.value.push({ id, cnName, parentId, parentCnName });
      handleTreeFlatData(children);
    });
  }
  // 处理节点展开
  function handleExpandedKeys(value: any) {
    expandedKeys.value = treeFlatData.value
      .map((item: any) => {
        if (item.cnName?.indexOf?.(value) > -1) {
          return findParent(item.cnName, treeData.value)?.id;
        }
        return null;
      })
      .filter((item: any, i: number, self: any) => item && self.indexOf(item) === i);
  }
  // 查找父节点
  function findParent(value: string, tree: any) {
    let parent: any = {};
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      const children = node?.childBizMetaAttrList || [];
      if (children?.length) {
        if (children.some((item: any) => item.cnName === value)) {
          parent = node;
        } else if (findParent(value, children)?.id) {
          parent = findParent(value, children);
        }
      }
    }
    return parent;
  }
  // 展开/收起节点时触发
  function handleExpand(keys: (string | number)[]) {
    expandedKeys.value = keys;
    autoExpandParent.value = false;
  }
  // 树节点点击事件
  function handleTreeNodeClick(id: string) {
    curId.value = id;
  }
  // 添加操作
  function handleAdd(parentId = '') {
    openModal(true, { parentId });
  }
  // 编辑操作
  function handleEdit(record: BizMetaAttrTreeModel) {
    openModal(true, { record, ifUpdate: true });
  }
  // 删除操作
  async function handleDel(id: string, childList: BizMetaAttrTreeModel[]) {
    if (childList?.length) {
      createMessage.error('存在子元属性，不可删除！');
      return;
    }
    await BizMetaArrApi.deleteBizMetaAttr(id);
    createMessage.success('删除成功！');
    handleQuery();
  }
  // 操作成功
  function handleSuccess() {
    closeModal();
    handleQuery();
  }
</script>

<style scoped lang="less"></style>
